# -*- coding: utf-8 -*-
import sys
import os
import hashlib
import json
import zipfile

def calculate_file_hash(data):
    """Calculate and return the SHA-256 hash of the file data"""
    hasher = hashlib.sha256()
    hasher.update(data)
    return hasher.hexdigest()

def get_file_size(data):
    """Return the size of the file data"""
    return len(data)

def query_zip_file(zip_path, file_path):
    """Query the hash and size of a specific file inside a ZIP archive."""
    # print(f"zip_path={zip_path};file_path={file_path}")

    try:
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            # Replace backslashes with forward slashes for compatibility
            file_path_normalized = file_path.replace('\\', '/')

            # Check if the file exists in the ZIP archive
            if file_path_normalized not in zip_ref.namelist():
                return json.dumps({"error": f"File {file_path} does not exist in the ZIP archive."})

            # Read the file data from the ZIP archive
            file_data = zip_ref.read(file_path_normalized)

            # Calculate the hash and size of the file
            file_hash = calculate_file_hash(file_data)
            file_size = get_file_size(file_data)

            result = {
                "file_path": file_path,
                "hash": file_hash,
                "size": file_size
            }

            return json.dumps(result, ensure_ascii=False)  # 确保输出JSON支持中文字符
    except FileNotFoundError:
        return json.dumps({"error": f"ZIP file {zip_path} does not exist."}, ensure_ascii=False)
    except zipfile.BadZipFile:
        return json.dumps({"error": f"Invalid ZIP file {zip_path}."}, ensure_ascii=False)

if __name__ == '__main__':
    # Ensure the correct number of arguments are provided
    if len(sys.argv) != 3:
        print(json.dumps({"error": "Two arguments required: ZIP file path and file path within the ZIP"}, ensure_ascii=False))
    else:
        zip_path = sys.argv[1]
        file_path = sys.argv[2]
        print(query_zip_file(zip_path, file_path))
        
# e.g. python m11_fileinzip_detail.py "D:\photo\base\相片2024\iPhone2024Q4.zip" "IMG_3672.JPEG"
# e.g. python m11_fileinzip_detail.py "D:\photo\base\相片2022\20220730_GZ_zoo.zip" "iCloud Photos/IMG_4834.JPEG"
